import React, { useState, useRef, useEffect } from 'react';
import { Card, Tag, Button } from 'antd-mobile';
import {
  CheckCircleOutline,
  ClockCircleOutline,
  LockOutline,
  FileOutline,
} from 'antd-mobile-icons';
import styles from './KBlist.less';
import BellaHeader from '@/components/header';
import { FootToolbar } from '@/components/footToolbar';
import { udp, useAsyncEffect } from '@cscec/udp-mobile-ui';
import { getList, queryDetail, queryDetailForThink, Uphistory } from './service';

// 定义单元类型
interface Unit {
  id: number;
  name: string;
  completionStatus: 0 | 1 | 2;// NOT_STUDY(0, "未学习"),STUDYING(1,"学习中") FINISH(2,"已学习");
  studyFlag?: 0 | 1;
}

// 定义学习类型
type StudyType = 'vocabulary' | 'article';

const KB1UnitList: React.FC = () => {
  const { id, name, imgurl } = udp.getQueryValue()
  const [units, setUnits] = useState<Unit[]>([]);
  const containerRef = useRef<HTMLDivElement>(null);
  const hasScrolledRef = useRef(false); // 防止重复滚动

  // 滚动到上次学习的单元
  const scrollToLastStudiedUnit = () => {
    if (hasScrolledRef.current || !containerRef.current) return;
    
    const lastStudiedCard = containerRef.current.querySelector(`.${styles['unit-card-last-studied']}`);
    if (lastStudiedCard) {
      // 延迟一点确保DOM完全渲染
      setTimeout(() => {
        lastStudiedCard.scrollIntoView({ 
          behavior: 'smooth', 
          block: 'center' 
        });
        hasScrolledRef.current = true;
      }, 300);
    }
  };

  // 处理学习按钮点击
  const handleStudyClick = async (unitId: number, studyType: StudyType) => {
    const unit: any = units.find(u => u.id === unitId);
    //console.log(unit)
    //获取主题 应该是Listen1是单词 Listen3是文章
    const res = await getList({ pageIndex: 1, pageSize: 999, unit_id: unit.id })
    const leng = res.record.length
    if (leng > 0) {
      //这里主题的配置不固定，先按照第一个主题是单词，最后一个是文章
      if (studyType == 'vocabulary') {
        Uphistory({
          textbookId: id,
          unitId: unit.id,
          topicId: res.record[0].id,
          completionStatus: 1, studyFlag: 1, historyType: 1
        }).then((rt) => {
          udp.open('/Textbook', { unit: unit.id, topic: res.record[0].id, title: unit.name })
        })
      } else {
        Uphistory({
          textbookId: id,
          unitId: unit.id,
          topicId: res.record[0].id,
          completionStatus: 1, studyFlag: 1, historyType: 0
        }).then((rt) => {
          udp.open('/ArticleStudy', { unit: unit.id, topic: res.record[leng - 1].id, title: unit.name })
        })
      }
    }
  };

  // 模拟加载动画
  useAsyncEffect(async () => {
    // const res = await queryDetail({ id: id })
    const res = await queryDetailForThink({id:id})
    setUnits(res.unitList)
  }, [id]);

  // 当units数据加载完成后，滚动到上次学习的位置
  useEffect(() => {
    if (units.length > 0) {
      scrollToLastStudiedUnit();
    }
  }, [units]);

  return (
    <div className={styles['kb1-container']} ref={containerRef}>
      {/* 头部 */}
      <BellaHeader title={name} />

      {/* 主要内容区 */}
      <main className={styles['main-content']}>
        {/* 单元列表 */}
        <div className={styles['unit-list']}>
          {units.map((unit: any) => (
            <Card
              key={unit.id}
              //className={`unit-card ${unit.isLastStudied ? 'last-studied' : ''}`}
              className={unit.studyFlag ? styles['unit-card-last-studied'] : styles['unit-card']}
            >
              {unit.studyFlag == 1 && (
                <div className={styles['last-study-badge']}>
                  <ClockCircleOutline />
                  <span>上次学习</span>
                </div>
              )}

              <div className={styles['unit-header']}>
                <h4 className={styles['unit-title']}>{unit.name}</h4>
                <Tag
                  color={unit.completionStatus === 2 ? 'success' : unit.completionStatus === 1 ? 'warning' : 'default'}
                  className={styles['completionStatus-tag']}
                >
                  {unit.completionStatus === 2 ? (
                    <>
                      <CheckCircleOutline />
                      <span>已学习</span>
                    </>
                  ) : unit.completionStatus === 1 ? (
                    <>
                      <ClockCircleOutline />
                      <span>学习中</span>
                    </>
                  ) : (
                    <>
                      <LockOutline />
                      <span>未学习</span>
                    </>
                  )}
                </Tag>
              </div>
              {
                //文章标识和单词标识
                unit.articleFlag == 1 && unit.wordFlag == 1 ? (
                  <div className={styles['study-buttons']}>
                    <Button
                      className={styles['vocab-btn']}
                      //disabled={unit.completionStatus === 'locked'}
                      onClick={() => handleStudyClick(unit.id, 'vocabulary')}
                    >
                      <FileOutline />
                      <span>单词学习</span>
                    </Button>
                    <Button
                      className={styles['article-btn']}
                      //disabled={unit.completionStatus === 'locked'}
                      onClick={() => handleStudyClick(unit.id, 'article')}
                    >
                      <FileOutline />
                      <span>文章学习</span>
                    </Button>
                  </div>
                ) : (
                  <></>
                )
              }
            </Card>
          ))}
        </div>

        {/* 鼓励语 */}
        <div className={styles['encouragement']}>
          <p>继续加油，你做得很棒！</p>
        </div>
      </main>

      {/* 底部导航 */}
      <FootToolbar />
    </div>
  );
};

export default KB1UnitList;